import { encrypt, decrypt } from '@/zero/utils/crypto';
import RenderAuthorize from './_components/Authorized';

/**
 *  key => 前端显示
 */
const defaultKey = `${process.env.PROJECT_CODE}_authorized_dd2815b7-b42e-5d79-88df-d87e3631af98`;

/**
 * 获取“当前权限” => ['']
 */
const getAuthorities = () => {
  let authorities;
  try {
    authorities = decrypt(localStorage.getItem(defaultKey))?.map(item =>
      typeof item === 'object' ? `${item.id}` : `${item}`,
    );
  } catch (e) {
    authorities = [];
  }
  return authorities;
};

/**
 * 获取“当前权限” => [{}]
 */
const getRawAuthorities = () => {
  let authorities;
  try {
    authorities = decrypt(localStorage.getItem(defaultKey))?.map(item =>
      typeof item === 'object'
        ? {
            ...item,
            id: `${item.id}`,
          }
        : {
            ...item,
            id: `${item}`,
          },
    );
  } catch (e) {
    authorities = [];
  }
  return authorities;
};

const getAuthority = o => {
  const array = [].concat(o);
  const authorities = getAuthorities().filter(item => array.includes(item));
  return authorities.length ? authorities : null;
};

const getRawAuthority = o => {
  const array = [].concat(o);
  const authorities = getRawAuthorities().filter(item =>
    array.includes(typeof item === 'object' ? `${item.id}` : `${item}`),
  );
  return authorities.length ? authorities : null;
};

/**
 * 初始化“权限组件”
 */
let Authorized = RenderAuthorize(getAuthorities()); // eslint-disable-line

/**
 * 重载“权限组件”
 */
const reloadAuthorized = () => {
  Authorized = RenderAuthorize(getAuthorities()); // 根据“当前权限”，重载“权限组件”
};

/**
 * 设置“当前权限”
 */
const setAuthorities = (authorities = []) => {
  localStorage.setItem(defaultKey, encrypt(authorities));
  reloadAuthorized();
};

export {
  Authorized,
  getAuthorities,
  getRawAuthorities,
  getAuthority,
  getRawAuthority,
  setAuthorities,
};
